Java

您所在的位置:网站首页 java sorted排序 Java

Java

2023-04-03 11:42| 来源: 网络整理| 查看: 265

sorted 方法用于元素排序

一、升序 List userList = new ArrayList(); // userInfo字段 UserId; Age; NickName; Sex 1:男 2:女; moneny零花钱 userList.add(new userInfo(1,24,"小明",1,new BigDecimal("11"))); userList.add(new userInfo(2,22,"小红",2,new BigDecimal("22"))); userList.add(new userInfo(3,24,"小张",1,new BigDecimal("33"))); List integers = Arrays.asList(1, 2, 3, 4); //年龄升序 List userList1 = userList.stream() .sorted(Comparator.comparing(userInfo::getAge)) .collect(Collectors.toList()); List filter1 = integers.stream() .sorted(Comparator.comparing(Integer::intValue)) .collect(Collectors.toList()); 复制代码

二、降序 reversed List userList2 = userList.stream() .sorted(Comparator.comparing(userInfo::getAge).reversed()) .collect(Collectors.toList()); List filter2 = integers.stream() .sorted(Comparator.comparing(Integer::intValue).reversed()) .collect(Collectors.toList()); 复制代码

三、多字段排序

关键字thenComparing

1.先以年龄升序 2.当年龄相同时,在以零花钱升序

List userList3 = userList.stream() .sorted(Comparator.comparing(userInfo::getAge).thenComparing(userInfo::getMoney)) .collect(Collectors.toList()); 复制代码

四、多字段区分升序降序

关键字thenComparing、Comparator.reverseOrder()

1.先以年龄升序 2.当年龄相同时,在以零花钱降序 Comparator.reverseOrder()

List userList3 = userList.stream() .sorted(Comparator.comparing(userInfo::getAge).thenComparing(userInfo::getMoney,Comparator.reverseOrder())) .collect(Collectors.toList()); 复制代码


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3